package code19_jdk8.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Test03 {

	public static void main(String[] args) {
		MyInter mi = (msg) -> System.out.println(msg);
		// 方法的引用
		mi = System.out::println;
		
		
		//testConSumer();
		//testSupplier();
		//testFunction();
		testPredicate();
	}
	private static void testConSumer() {
		consume(5000,
				// 具体的消费
				m -> System.out.println( "花费了 " + m + " 元, 买了把大宝剑!" )
				);
	}
	// 消费型接口: 用钱取消费(具体不清楚消费什么)
	public static void consume(double money, Consumer<Double> consumer) {
		consumer.accept(money);
	}
	
	private static void testSupplier() {
		// 具体的生产规则
		Supplier<Integer> supplier = () -> (int)(Math.random()*10);
		List<Integer> nums = getNums(4, supplier);
		System.out.println(nums);
	}
	// 供给型接口: 生产指定个数个整数(没有具体要求)
	public static List<Integer> getNums(int count, Supplier<Integer> supplier) {
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < count; i++) {
			Integer num = supplier.get();
			list.add(num);
		}
		return list;
	}
	
	private static void testFunction() {
		// 具体的处理:获取字符串的长度
		Function<String, Integer> fun = t -> t.length();
		fun = String::length;// 方法的引用
		
		Integer handler = strHandler("helloworld", fun);
		System.out.println("handler:"+handler);
	}
	// 函数型接口: 处理字符串, 获取字符串的数值表示(没有特别要求)
	public static Integer strHandler(String str, Function<String, Integer> fun) {
		Integer apply = fun.apply(str);
		return apply;
	}
	
	private static void testPredicate() {
		List<String> list = Arrays.asList("aa", "bbb", "c", "d");
		// 具体的条件
		Predicate<String> p = s -> s.length()>=2;
		List<String> filter = strFilter(list, p);
		System.out.println("filter:"+filter);
	}
	// 断言型接口: 将满足条件(条件不清楚)的字符串收集到集合中
	public static List<String> strFilter(List<String> list, Predicate<String> p) {
		List<String> strs = new ArrayList<String>();
		for (String str : list) {
			// 判断是否符合条件
			if ( p.test(str) ) {
				strs.add(str);
			}
		}
		return strs;
	}
	
	
}

// 函数式接口
@FunctionalInterface // 对于函数式接口，建议加上该注解
interface MyInter {
	void fun1(String msg);
	//void fun2(String msg);
}